<template>
  <div class="search-filter-container">
    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="search-input-wrapper">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索图片名称、标签或文案内容..."
          size="large"
          clearable
          @input="handleSearchInput"
          @clear="handleSearchClear"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #suffix>
            <el-button 
              type="primary" 
              :icon="Search"
              @click="handleSearch"
              :loading="searching"
            >
              搜索
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 搜索建议 -->
      <div v-if="searchSuggestions.length > 0" class="search-suggestions">
        <div class="suggestions-header">
          <span>搜索建议</span>
          <el-button 
            text 
            size="small" 
            @click="clearSuggestions"
          >
            清除
          </el-button>
        </div>
        <div class="suggestions-list">
          <el-tag
            v-for="suggestion in searchSuggestions"
            :key="suggestion.text"
            class="suggestion-item"
            @click="handleSuggestionClick(suggestion.text)"
          >
            {{ suggestion.text }}
            <span class="suggestion-count">({{ suggestion.usageCount }})</span>
          </el-tag>
        </div>
      </div>
    </div>
    
    <!-- 筛选器 -->
    <div class="filter-section">
      <div class="filter-header">
        <h3>筛选条件</h3>
        <el-button 
          text 
          size="small" 
          @click="clearAllFilters"
          v-if="hasActiveFilters"
        >
          清除所有
        </el-button>
      </div>
      
      <div class="filter-content">
        <!-- 标签筛选 -->
        <div class="filter-group">
          <div class="filter-title">
            <el-icon><Collection /></el-icon>
            标签筛选
          </div>
          <div class="tag-filter">
            <div class="selected-tags" v-if="selectedTags.length > 0">
              <el-tag
                v-for="tag in selectedTags"
                :key="tag"
                closable
                @close="removeTag(tag)"
                class="selected-tag"
              >
                {{ tag }}
              </el-tag>
            </div>
            
            <div class="popular-tags">
              <div class="tags-header">
                <span>热门标签</span>
                <el-button 
                  text 
                  size="small" 
                  @click="loadMoreTags"
                  v-if="!showAllTags"
                >
                  更多
                </el-button>
              </div>
              <div class="tags-list">
                <el-tag
                  v-for="tag in displayTags"
                  :key="tag.tagName"
                  :class="{ 'active': selectedTags.includes(tag.tagName) }"
                  class="tag-option"
                  @click="toggleTag(tag.tagName)"
                >
                  {{ tag.tagName }}
                  <span class="tag-count">({{ tag.usageCount }})</span>
                </el-tag>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 文件类型筛选 -->
        <div class="filter-group">
          <div class="filter-title">
            <el-icon><Document /></el-icon>
            文件类型
          </div>
          <el-checkbox-group v-model="selectedMimeTypes" @change="handleMimeTypeChange">
            <el-checkbox label="image/jpeg">JPEG</el-checkbox>
            <el-checkbox label="image/png">PNG</el-checkbox>
            <el-checkbox label="image/gif">GIF</el-checkbox>
            <el-checkbox label="image/webp">WebP</el-checkbox>
          </el-checkbox-group>
        </div>
        
        <!-- 尺寸筛选 -->
        <div class="filter-group">
          <div class="filter-title">
            <el-icon><FullScreen /></el-icon>
            图片尺寸
          </div>
          <div class="size-filter">
            <div class="size-range">
              <label>宽度:</label>
              <el-input-number
                v-model="sizeFilter.minWidth"
                :min="0"
                :max="10000"
                size="small"
                placeholder="最小"
                @change="handleSizeChange"
              />
              <span>-</span>
              <el-input-number
                v-model="sizeFilter.maxWidth"
                :min="0"
                :max="10000"
                size="small"
                placeholder="最大"
                @change="handleSizeChange"
              />
            </div>
            <div class="size-range">
              <label>高度:</label>
              <el-input-number
                v-model="sizeFilter.minHeight"
                :min="0"
                :max="10000"
                size="small"
                placeholder="最小"
                @change="handleSizeChange"
              />
              <span>-</span>
              <el-input-number
                v-model="sizeFilter.maxHeight"
                :min="0"
                :max="10000"
                size="small"
                placeholder="最大"
                @change="handleSizeChange"
              />
            </div>
          </div>
        </div>
        
        <!-- 文件大小筛选 -->
        <div class="filter-group">
          <div class="filter-title">
            <el-icon><Files /></el-icon>
            文件大小
          </div>
          <div class="file-size-filter">
            <el-slider
              v-model="fileSizeRange"
              range
              :min="0"
              :max="100"
              :format-tooltip="formatFileSizeTooltip"
              @change="handleFileSizeChange"
            />
            <div class="size-labels">
              <span>{{ formatFileSize(fileSizeRange[0] * 1024 * 1024) }}</span>
              <span>{{ formatFileSize(fileSizeRange[1] * 1024 * 1024) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 时间筛选 -->
        <div class="filter-group">
          <div class="filter-title">
            <el-icon><Calendar /></el-icon>
            上传时间
          </div>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
            size="small"
          />
        </div>
        
        <!-- AI识别状态筛选 -->
        <div class="filter-group">
          <div class="filter-title">
            <el-icon><MagicStick /></el-icon>
            AI识别状态
          </div>
          <el-radio-group v-model="aiStatusFilter" @change="handleAiStatusChange">
            <el-radio label="">全部</el-radio>
            <el-radio label="SUCCESS">识别成功</el-radio>
            <el-radio label="PENDING">识别中</el-radio>
            <el-radio label="FAILED">识别失败</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
    
    <!-- 排序选项 -->
    <div class="sort-section">
      <div class="sort-header">
        <h3>排序方式</h3>
      </div>
      <div class="sort-options">
        <el-select v-model="sortBy" @change="handleSortChange" size="small">
          <el-option label="上传时间" value="createdAt" />
          <el-option label="文件大小" value="fileSize" />
          <el-option label="使用频率" value="usageCount" />
          <el-option label="文件名称" value="originalName" />
        </el-select>
        <el-select v-model="sortDir" @change="handleSortChange" size="small">
          <el-option label="降序" value="desc" />
          <el-option label="升序" value="asc" />
        </el-select>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { 
  Search, Collection, Document, FullScreen, Files, Calendar, MagicStick 
} from '@element-plus/icons-vue'
import type { SearchSuggestion, TagCloudItem, SearchCriteria } from '@/types'
import { formatFileSize, debounce } from '@/utils'

interface Props {
  popularTags?: TagCloudItem[]
  loading?: boolean
}

interface Emits {
  (e: 'search', criteria: SearchCriteria): void
  (e: 'get-suggestions', keyword: string): void
  (e: 'load-popular-tags'): void
}

const props = withDefaults(defineProps<Props>(), {
  popularTags: () => [],
  loading: false
})

const emit = defineEmits<Emits>()

// 响应式数据
const searchKeyword = ref('')
const searching = ref(false)
const searchSuggestions = ref<SearchSuggestion[]>([])
const selectedTags = ref<string[]>([])
const selectedMimeTypes = ref<string[]>([])
const sizeFilter = ref({
  minWidth: undefined as number | undefined,
  maxWidth: undefined as number | undefined,
  minHeight: undefined as number | undefined,
  maxHeight: undefined as number | undefined
})
const fileSizeRange = ref([0, 100])
const dateRange = ref<[string, string] | null>(null)
const aiStatusFilter = ref('')
const sortBy = ref('createdAt')
const sortDir = ref('desc')
const showAllTags = ref(false)

// 计算属性
const displayTags = computed(() => {
  return showAllTags.value ? props.popularTags : props.popularTags.slice(0, 10)
})

const hasActiveFilters = computed(() => {
  return selectedTags.value.length > 0 ||
         selectedMimeTypes.value.length > 0 ||
         sizeFilter.value.minWidth !== undefined ||
         sizeFilter.value.maxWidth !== undefined ||
         sizeFilter.value.minHeight !== undefined ||
         sizeFilter.value.maxHeight !== undefined ||
         fileSizeRange.value[0] > 0 ||
         fileSizeRange.value[1] < 100 ||
         dateRange.value !== null ||
         aiStatusFilter.value !== ''
})

// 防抖搜索
const debouncedSearch = debounce(() => {
  handleSearch()
}, 500)

const debouncedGetSuggestions = debounce((keyword: string) => {
  if (keyword.length > 1) {
    emit('get-suggestions', keyword)
  } else {
    searchSuggestions.value = []
  }
}, 300)

// 方法
const handleSearchInput = (value: string) => {
  debouncedGetSuggestions(value)
  // 移除自动搜索，只在用户主动搜索时触发
}

const handleSearchClear = () => {
  searchSuggestions.value = []
  handleSearch()
}

const handleSearch = () => {
  searching.value = true
  
  const criteria: SearchCriteria = {
    keyword: searchKeyword.value || undefined,
    tags: selectedTags.value.length > 0 ? selectedTags.value : undefined,
    mimeTypes: selectedMimeTypes.value.length > 0 ? selectedMimeTypes.value : undefined,
    minWidth: sizeFilter.value.minWidth,
    maxWidth: sizeFilter.value.maxWidth,
    minHeight: sizeFilter.value.minHeight,
    maxHeight: sizeFilter.value.maxHeight,
    minFileSize: fileSizeRange.value[0] > 0 ? fileSizeRange.value[0] * 1024 * 1024 : undefined,
    maxFileSize: fileSizeRange.value[1] < 100 ? fileSizeRange.value[1] * 1024 * 1024 : undefined,
    startDate: dateRange.value?.[0],
    endDate: dateRange.value?.[1],
    sortBy: sortBy.value,
    sortDir: sortDir.value
  }
  
  // 添加AI状态筛选
  if (aiStatusFilter.value) {
    criteria.aiStatus = aiStatusFilter.value as 'SUCCESS' | 'PENDING' | 'FAILED'
  }
  
  emit('search', criteria)
  
  setTimeout(() => {
    searching.value = false
  }, 1000)
}

const handleSuggestionClick = (suggestion: string) => {
  searchKeyword.value = suggestion
  searchSuggestions.value = []
  handleSearch()
}

const clearSuggestions = () => {
  searchSuggestions.value = []
}

const toggleTag = (tagName: string) => {
  const index = selectedTags.value.indexOf(tagName)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tagName)
  }
  handleSearch()
}

const removeTag = (tagName: string) => {
  const index = selectedTags.value.indexOf(tagName)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
    handleSearch()
  }
}

const loadMoreTags = () => {
  showAllTags.value = true
  emit('load-popular-tags')
}

const handleMimeTypeChange = () => {
  debouncedSearch()
}

const handleSizeChange = () => {
  debouncedSearch()
}

const handleFileSizeChange = () => {
  debouncedSearch()
}

const handleDateRangeChange = () => {
  debouncedSearch()
}

const handleAiStatusChange = () => {
  debouncedSearch()
}

const handleSortChange = () => {
  debouncedSearch()
}

const clearAllFilters = () => {
  selectedTags.value = []
  selectedMimeTypes.value = []
  sizeFilter.value = {
    minWidth: undefined,
    maxWidth: undefined,
    minHeight: undefined,
    maxHeight: undefined
  }
  fileSizeRange.value = [0, 100]
  dateRange.value = null
  aiStatusFilter.value = ''
  handleSearch()
}

const formatFileSizeTooltip = (value: number) => {
  return formatFileSize(value * 1024 * 1024)
}

// 生命周期
onMounted(() => {
  emit('load-popular-tags')
  // 移除初始搜索，让父组件控制初始加载
})

// 暴露方法给父组件
defineExpose({
  setSuggestions: (suggestions: SearchSuggestion[]) => {
    searchSuggestions.value = suggestions
  }
})
</script>

<style scoped>
.search-filter-container {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  color: white;
}

/* 搜索栏样式 */
.search-section {
  margin-bottom: 30px;
}

.search-input-wrapper {
  margin-bottom: 15px;
}

.search-input-wrapper :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: none;
}

.search-input-wrapper :deep(.el-input__inner) {
  color: white;
}

.search-input-wrapper :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

.search-suggestions {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  padding: 15px;
}

.suggestions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.suggestions-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.suggestion-item {
  cursor: pointer;
  transition: all 0.2s ease;
}

.suggestion-item:hover {
  transform: scale(1.05);
}

.suggestion-count {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

/* 筛选器样式 */
.filter-section {
  margin-bottom: 30px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.filter-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.filter-group {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  padding: 15px;
}

.filter-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 15px;
  color: rgba(255, 255, 255, 0.9);
}

/* 标签筛选样式 */
.selected-tags {
  margin-bottom: 15px;
}

.selected-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tags-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.7);
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-option {
  cursor: pointer;
  transition: all 0.2s ease;
}

.tag-option:hover {
  transform: scale(1.05);
}

.tag-option.active {
  background-color: #409EFF;
  color: white;
}

.tag-count {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

/* 尺寸筛选样式 */
.size-filter {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.size-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.size-range label {
  width: 40px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

.size-range span {
  color: rgba(255, 255, 255, 0.6);
}

/* 文件大小筛选样式 */
.file-size-filter {
  padding: 0 10px;
}

.size-labels {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

/* 排序样式 */
.sort-section {
  margin-bottom: 20px;
}

.sort-header h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: 600;
}

.sort-options {
  display: flex;
  gap: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-filter-container {
    padding: 15px;
  }
  
  .filter-content {
    gap: 15px;
  }
  
  .size-range {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .sort-options {
    flex-direction: column;
  }
}
</style>